import 'dart:async';

import 'package:bike_ride/common/mvvm/base_page.dart';
import 'package:bike_ride/common/util/extension.dart';
import 'package:bike_ride/common/util/format.dart';
import 'package:bike_ride/common/util/hysize_fit.dart';
import 'package:bike_ride/common/widget/error.dart';
import 'package:bike_ride/common/widget/page_title_widget.dart';
import 'package:bike_ride/common/widget/round_tab_indicator.dart';
import 'package:bike_ride/generated/l10n.dart';
import 'package:bike_ride/model/cycle_record/view_model/cycle_record_vm.dart';
import 'package:bike_ride/model/cyling/model/unpay_info_m.dart';
import 'package:bike_ride/res/style/color_styles.dart';
import 'package:bike_ride/res/style/theme_styles.dart';
import 'package:bike_ride/router/navigator_util.dart';
import 'package:bike_ride/router/routers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

final tabs = {
  2: S.current.unPaid,
  3: S.current.completed,
  5: S.current.refundOrder,
};
///行程记录页面
class CyclingRecordView extends BaseStatefulPage<CyclingRecordViewModel> {
  const CyclingRecordView({super.key});

  @override
  CyclingRecordViewState createState() => CyclingRecordViewState();
}

class CyclingRecordViewState
    extends BaseStatefulPageState<CyclingRecordView, CyclingRecordViewModel> with SingleTickerProviderStateMixin{
  late TabController _tabController;

  final key1 = GlobalKey<_TabBarViewWidgetState>();
  final key2 = GlobalKey<_TabBarViewWidgetState>();
  final key3 = GlobalKey<_TabBarViewWidgetState>();

  @override
  void initAttribute() {}

  @override
  void initObserver() {
    _tabController = TabController(vsync: this, length: tabs.length, initialIndex: 0)..addListener(() {
      if (_tabController.indexIsChanging) {
        setState(() {

        });
        Future.delayed(const Duration(milliseconds: 500),()=>_refresh());
      }
    });
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _refresh();
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  CyclingRecordViewModel viewBindingViewModel() {
    return CyclingRecordViewModel()..viewState = this;
  }

  Future _refresh()async{
    key1.currentState?.refresh(showLoading: true);
  }

  @override
  Widget appBuild(BuildContext context) {
    return Scaffold(
        backgroundColor: ColorStyles.color_F3F4F5,
        body: Column(
          children: [
            PageTitleWidget(title: S.current.mineTravelRecord),
            Container(
              decoration: BoxDecoration(
                color: ColorStyles.color_FFFFFF,
                boxShadow: [
                  BoxShadow(
                    color: ColorStyles.color_000000.withOpacity(0.2),
                    blurRadius: 2,
                    offset: const Offset(0, 1),
                  ),
                ],
              ),
              child: TabBar(
                controller: _tabController,
                dividerHeight: 0,
                indicatorSize: TabBarIndicatorSize.tab,
                indicator: RoundUnderlineTabIndicator(
                    borderSide: BorderSide(
                      width: 2.rpx,
                      color: Theme.of(context).colorScheme.primary,
                    )
                ),
                labelStyle: TextStyle(color: Colors.black87,fontSize: 32.rpx,fontWeight: FontWeight.w600),
                unselectedLabelStyle: TextStyle(color: Colors.black87,fontSize: 30.rpx,fontWeight: FontWeight.w400),
                tabs: [for (final tab in tabs.values) Padding(padding: const EdgeInsets.only(bottom: 5),child: VgTab(text: tab,),)],
              ),
            ),
            Expanded(child: _TabBarViewWidget(key: key1,orderStatusType: tabs.keys.toList()[_tabController.index], viewModel: viewModel!),)
          ],
        ));
  }
}

class _TabBarViewWidget extends StatefulWidget {
  final int orderStatusType;
  final CyclingRecordViewModel viewModel;
  const _TabBarViewWidget({super.key, required this.orderStatusType, required this.viewModel});

  @override
  State<_TabBarViewWidget> createState() => _TabBarViewWidgetState();
}

class _TabBarViewWidgetState extends State<_TabBarViewWidget>{

  final StreamController<List<UnPayInfoM>> _streamController = StreamController();
  final ScrollController _scrollController = ScrollController();
  List<UnPayInfoM> _list = [];
  int _page = 1;
  final int _size = 10;
  bool _haveMore = true;
  final refreshIndicatorKey = GlobalKey<RefreshIndicatorState>();

  Future refresh({int bPage = 1,bool showLoading = false})async{
    if(widget.orderStatusType == 2){
      _refreshUnPay(bPage: bPage, showLoading: showLoading);
    }else if(widget.orderStatusType == 3){
      _refreshPayed(bPage: bPage,showLoading: showLoading);
    }else if(widget.orderStatusType == 5){
      _refreshPayed(bPage: bPage,status: 2,showLoading: showLoading);
    }
  }

  Future _refreshUnPay({int bPage = 1,bool showLoading = false})async{
    if(showLoading){
      EasyLoading.show();
    }
    final data = await widget.viewModel.getUnPayOrder(bPage);
    EasyLoading.dismiss();
    if (data.isNotEmpty && data[0].errorMsg != null) {
      _streamController.safetyError(data[0].errorMsg.toString());
    } else {
      if (bPage == 1) {
        _list = data;
      } else {
        _list.addAll(data);
      }
      _page = bPage + 1;
      _haveMore = data.length <= _size;
      _streamController.safetyAdd(_list);
    }
  }

  Future _refreshPayed({int bPage = 1,int? status,bool showLoading = false})async{
    if(showLoading){
      EasyLoading.show();
    }
    final data = await widget.viewModel.getFinishOrderDetail(bPage,status: status);
    EasyLoading.dismiss();
    if (data.isNotEmpty && data[0].errorMsg != null) {
      _streamController.safetyError(data[0].errorMsg.toString());
    } else {
      if (bPage == 1) {
        _list = data;
      } else {
        _list.addAll(data);
      }
      _page = bPage + 1;
      _haveMore = data.length <= _size;
      _streamController.safetyAdd(_list);
    }
  }

  @override
  void dispose() {
    _streamController.close();
    _scrollController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      if (_scrollController.position.maxScrollExtent ==
          _scrollController.position.pixels) {
        if (_haveMore) {
          refresh(bPage: _page);
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<List<UnPayInfoM>>(
      stream: _streamController.stream,
        initialData: const [],
        builder: (context,snapshot){
          final hasData = snapshot.data != null &&
              (snapshot.data!.isNotEmpty || _list.isNotEmpty);
          return RefreshIndicator(
            key: refreshIndicatorKey,
            onRefresh: ()=>refresh(showLoading: true),
            child: ListView.builder(
              controller: _scrollController,
              padding: EdgeInsets.symmetric(vertical: 20.rpx),
              itemCount: hasData ? _list.length : 1,
              physics: const AlwaysScrollableScrollPhysics(),
              itemBuilder: (context, index) {
                if (hasData) {
                  return Column(
                    children: [
                      GestureDetector(
                        onTap: (){
                          switch(_list[index].orderStatus){
                            case 1:
                              NavigatorUtil.push(context, Routers.cyclingView,arguments: {"order_id": _list[index].orderId}).then((value){
                                refreshIndicatorKey.currentState?.show();
                              });
                              break;
                            case 2:
                            case 3:
                            case 4:
                            case 5:
                              NavigatorUtil.push(context, Routers.payView,arguments: {"order_id": _list[index].orderId}).then((value){
                                refreshIndicatorKey.currentState?.show();
                              });
                              break;
                          }
                        },
                        child: _ItemWidget(
                            onRefresh: () => refreshIndicatorKey.currentState?.show(),
                            model: _list[index]),
                      ),
                      if (index == _list.length - 1)
                        ...[
                          const SizedBox(height: 4,),
                          Center(
                              child: Text(
                                S.current.noMore,
                                style: TextStyle(
                                    color: Colors.grey.withOpacity(0.6)),
                              ))
                        ]
                    ],
                  );
                }
                return Center(
                  child: ErrorInfoWidget(
                    retry: ()=>refreshIndicatorKey.currentState?.show(),
                    errorMsg: snapshot.error,
                  ),
                );
              },
            ),
          );
    });
  }
}


class _ItemWidget extends StatelessWidget {
  final UnPayInfoM model;
  final Function() onRefresh;
  const _ItemWidget({required this.model, required this.onRefresh});

  @override
  Widget build(BuildContext context) {
    final primaryColor = Theme.of(context).colorScheme.primary;
    final firstTextStyle = TextStyle(fontSize: 28.rpx,color: ColorStyles.color_666666);
    final secondTextStyle = TextStyle(fontSize: 28.rpx,color: ColorStyles.color_333333);
    Widget buildLocationText(bool start,String text){
      return Row(
        children: [
          Icon(start?Icons.location_on_outlined:Icons.location_on,size: 32.rpx,color: ColorStyles.color_333333,),
          ConstrainedBox(
            constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width - 6 *ThemeStyles.pagePaddingHorizontal),
            child: Text(
              text,
              maxLines: 2,
              style: firstTextStyle.copyWith(fontSize: 24.rpx),
            ),
          ),
        ],
      );
    }
    return Container(
      margin: EdgeInsets.symmetric(horizontal: ThemeStyles.pagePaddingHorizontal,vertical: 8.rpx),
      padding: EdgeInsets.symmetric(horizontal: 24.rpx,vertical: 16.rpx),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(32.rpx),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 8.rpx,
              spreadRadius: 2.rpx,
              offset: const Offset(0, 2),
            )
          ]
      ),
      child: Column(
        children: [
          Row(
            children: [
              Icon(Icons.access_time,size: 26.rpx,color: ColorStyles.color_333333,),
              Text(formatTimestamp(model.startTime),style: firstTextStyle,),
              const Spacer(),
              Text(tabs[model.orderStatus]??'-',style: firstTextStyle.copyWith(color: primaryColor),),
              Icon(Icons.keyboard_arrow_right_rounded,size: 32.rpx,color: primaryColor,),
            ],
          ),
          Container(
            margin: EdgeInsets.symmetric(vertical: 8.rpx),
            padding: EdgeInsets.symmetric(horizontal: 8.rpx,vertical: 8.rpx),
            decoration: BoxDecoration(
                color: ColorStyles.color_F5F5F5,
                borderRadius: BorderRadius.circular(8.rpx)
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                buildLocationText(true,model.startAddress??'-'),
                buildLocationText(false,model.returnAddress??'-'),
              ],
            ),
          ),
          Row(
            children: [
              Text(S.current.rideTime,style: firstTextStyle,),
              Text(durationTransform(((model.ridingTime??0) * 60).toInt(),isEasy: true,needZeroFill: false)),
              const Spacer(),
              Text('￥',style: secondTextStyle,),
              Text('${model.amount}',style: secondTextStyle.copyWith(fontSize: 32.rpx),),
              if(model.orderStatus == 2)
                ...[
                  SizedBox(width: 16.rpx,),
                  Container(
                    width: 120.rpx,
                    height: 48.rpx,
                    padding: EdgeInsets.only(left: 8.rpx,right:8.rpx,bottom: 4.rpx),
                    decoration: BoxDecoration(
                        color: Theme.of(context).colorScheme.primary,
                        borderRadius: BorderRadius.circular(32.rpx)
                    ),
                    child: Center(
                      child: Text(S.current.goRefund,style: TextStyle(fontSize: 28.rpx,color: ColorStyles.color_FFFFFF),)
                    )
                  )
                ]
            ],
          ),
          if(model.orderStatus == 5)
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Text('(${S.current.refundByWay})',style: secondTextStyle.copyWith(color: Colors.redAccent),)
              ],
            )
        ],
      ),
    );
  }
}
